//
//  SelectColorSubView.swift
//  CreateMyCode
//
//  Created by zhibao on 2024/2/20.
//

import UIKit
typealias selectColorBlock = (_ dic:[String:Any])->()
class SelectColorSubView: LazyScrollSubView,UICollectionViewDelegate,UICollectionViewDataSource {
    var selectBlock:selectColorBlock?
    var itemWH:CGFloat  = 0
    var margin:CGFloat = 0
    var dic = [AnyHashable:Any]()
    var flag = true
    let layout = UICollectionViewFlowLayout()
    var collectionView:MYCollectionView!
    var array = [[String:Any]]()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    override func reloadData(withDict dict: [AnyHashable : Any]!) {
        dic = dict
        if flag {
            flag = false
            self.initView()
            self.getData()
        }
    }
    
    fileprivate func getData(){
        let title = dic["title"] as! String
        if title == LocalizedString("码眼"){
            
            //外框
            var outDic = [String:Any]()
            outDic["title"] = LocalizedString("外框")
            
            var outArray = [[String:String]]()
            let clearOutDic = [
                "type":LocalizedString("外框"),
                "img":"trash",
                "value":CLEARFLAG
            ]
            outArray.append(clearOutDic)
            
            for i in 0 ..< 10 {
                let value = "eye_Outer_\(i)"
                let dic = [
                    "type":LocalizedString("外框"),
                    "img":value,
                    "value":value.replacingOccurrences(of: "_", with: "")
                ]
                outArray.append(dic)
            }
            outDic["eyes"] = outArray
            array.append(outDic)
            
            //内框
            var inDic = [String:Any]()
            inDic["title"] = LocalizedString("内框")
            
            var inArray = [[String:String]]()
            let clearInDic = [
                "type":LocalizedString("内框"),
                "img":"trash",
                "value":CLEARFLAG
            ]
            inArray.append(clearInDic)
            
            for i in 0 ..< 10 {
                let value = "eye_Inner_\(i)"
                let dic = [
                    "type":LocalizedString("内框"),
                    "img":value,
                    "value":value.replacingOccurrences(of: "_", with: "")
                ]
                inArray.append(dic)
            }
            inDic["eyes"] = inArray
            array.append(inDic)
        }else{
            var colorDic = [String:Any]()
            var colorArray = [[String:Any]]()
            var type  = LocalizedString("前景色")
            var colors = ["#781111","#0E467A","#127C23","#128280","#66670C","#0B887C","#730460","#39278C","#9A0000","#784611","#2B5052","#332B52","#4B2B52","#873D6A","#7F3D87","#473D87","#968548","#43703D","#327090"]
            
            if title == LocalizedString("背景色") {
                type = LocalizedString("背景色")
                colors = ["#F2C7C7","#D4E8FA","#C7EDCE","#CAF0F0","#F2F2D0","#CFE2E0","#EFD4EB","#E2DDFD","#E3D3E9","#F9EDE6","#F9E6F4","#E6E7F9","#E6F8F9","#E6F9EA","#F2F9E6","#F9F3E6","#E4ECFF","#F4F2FF","#FFF2FC"]
            }
            
            let clearDic = [
                "type":type,
                "img":"trash",
                "value":CLEARFLAG
            ]
            colorArray.append(clearDic)
            
            for color in colors {
                let dic = [
                    "type":type,
                    "value":color
                ]
                colorArray.append(dic)
            }
            colorDic["eyes"] = colorArray
            array.append(colorDic)
        }
        DLog(message: "array==\(array)")
    }
    
    fileprivate func initView(){
        layout.scrollDirection = .vertical
        collectionView = MYCollectionView(frame: self.bounds, collectionViewLayout: layout)
        collectionView.alwaysBounceVertical = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.contentInset = UIEdgeInsets(top: 0, left: 10, bottom: 10, right: 10)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.removeMJRefresh()
        collectionView.keyboardDismissMode = .onDrag
        self.addSubview(collectionView)
        collectionView.noDataType = .TableViewNoDataType_FILE
        collectionView.mj_footer?.endRefreshingWithNoMoreData()
        collectionView.register(SelectColorSubHeadView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "SelectColorSubHeadView")
        collectionView.register(TZTestCell.self, forCellWithReuseIdentifier: "TZTestCell6")
        let btnWidth:CGFloat = (SCREEN_WIDTH -  11 * pixw(p: 10)) / 10
        layout.itemSize = CGSizeMake(btnWidth, btnWidth)
        margin = pixw(p: 10)
        layout.minimumInteritemSpacing = margin
        layout.minimumLineSpacing = margin
        layout.headerReferenceSize = CGSize(width: SCREEN_WIDTH, height: pixw(p: 40))
        self.collectionView.collectionViewLayout = layout
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
extension SelectColorSubView{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let headView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "SelectColorSubHeadView", for: indexPath) as! SelectColorSubHeadView
            let title = array[indexPath.section]["title"] as? String ?? ""
            if (title != "") {
                headView.titleLabel.text = title
            }else{
                headView.titleLabel.text = ""
            }
            return headView
        }else{
            return UICollectionReusableView()
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return (array[section]["eyes"] as! [[String:Any]]).count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TZTestCell6", for: indexPath) as! TZTestCell
        let title = dic["title"] as! String
        let eyes = array[indexPath.section]["eyes"] as! [[String:String]]
        if title == LocalizedString("码眼"){
            cell.imageView.image = UIImage(named:eyes[indexPath.row]["img"] ?? "")
        }else{
            cell.imageView.image = nil
            let color = eyes[indexPath.row]["value"] ?? ""
            cell.imageView.backgroundColor = MYColor.color(withHexString: color)
        }
        
        if indexPath.row == 0 {
            if eyes[indexPath.row]["img"] != nil {
                cell.imageView.image = nil
                cell.deleteBtn.setImage(UIImage(systemName: eyes[indexPath.row]["img"]!), for: .normal)
                cell.deleteBtn.isUserInteractionEnabled = false
            }
        }
        cell.gifLable.isHidden = true
        cell.deleteBtn.tag = indexPath.item
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let eyes = array[indexPath.section]["eyes"] as! [[String:String]]
        let tempDic = eyes[indexPath.row]
        if (selectBlock != nil) {
            selectBlock!(tempDic)
        }
    }
}
